/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.front.web.cart;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.base.Strings;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.common.utils.CommonParameter;
import com.thinkgem.jeesite.common.utils.Message;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.accountinfo.entity.AccountInfo;
import com.thinkgem.jeesite.modules.accountinfo.entity.AccountInfoAddress;
import com.thinkgem.jeesite.modules.accountinfo.service.AccountInfoAddressService;
import com.thinkgem.jeesite.modules.accountinfo.service.AccountInfoService;
import com.thinkgem.jeesite.modules.front.entity.cart.GenCart;
import com.thinkgem.jeesite.modules.front.service.cart.GenCartService;
import com.thinkgem.jeesite.modules.product.entity.product.GenProduct;
import com.thinkgem.jeesite.modules.product.service.product.GenProductService;
import com.thinkgem.jeesite.modules.shop.constant.order.ShopOrderConstant;
import com.thinkgem.jeesite.modules.shop.entity.info.ShopOrderInfo;
import com.thinkgem.jeesite.modules.shop.entity.order.ShopOrder;
import com.thinkgem.jeesite.modules.shop.service.order.ShopOrderService;
import com.thinkgem.jeesite.modules.sys.entity.Dict;
import com.thinkgem.jeesite.modules.sys.service.DictService;

/**
 * 购物车Controller
 * @author Egan
 * @version 2016-12-15
 */
@Controller
@RequestMapping(value = "${frontPath}/front/cart/genCart")
public class GenCartController extends BaseController {

	@Autowired
	GenCartService genCartService;
	
	@Autowired
	GenProductService genProductService;
	
	@Autowired
	AccountInfoAddressService accountInfoAddressService;
	
	@Autowired
	DictService dictService;
	
	@Autowired
	ShopOrderService shopOrderService;
	
	@Autowired
	AccountInfoAddressService addressService;
	
	@Autowired
	AccountInfoService accountInfoService;
	
	@ModelAttribute
	public GenCart get(@RequestParam(required=false) String id) {
		GenCart entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = genCartService.get(id);
		}
		if (entity == null){
			entity = new GenCart();
		}
		return entity;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = {"list", ""})
	public String list(GenCart genCart, HttpServletRequest request, HttpServletResponse response,HttpSession session, Model model) {
		String message = request.getParameter("message");
		AccountInfo user = (AccountInfo)session.getAttribute("user");
		Object object = CacheUtils.get(user.getId());
		List<GenCart> carts = null;
		genCart.setAccountid(Long.parseLong(user.getId()));
		List<GenCart> cartslist = genCartService.findList(genCart);
		if (object != null) {
			carts  = (List<GenCart>) object;
			if(carts.size()!=genCartService.findList(genCart).size()){
			    carts = cartslist;
	            CacheUtils.put(user.getId(), carts);
			}
		} else {
		    carts = cartslist;
			CacheUtils.put(user.getId(), carts);
		}
		model.addAttribute("count", carts.size());
		model.addAttribute("path", CommonParameter.uploadPath);
		model.addAttribute("carts", carts);
		
		if ("1".equals(message)) {
			model.addAttribute("message", Message.getContent("genCart.number"));
		}
		return "modules/shop/trolley/index";
	}

	@RequestMapping(value = "save")
	@ResponseBody
	public Object save(String productid,HttpSession session,int amt,
			Model model, RedirectAttributes redirectAttributes) {
		AccountInfo user = (AccountInfo)session.getAttribute("user");
		GenCart genCart = new GenCart();
		genCart.setAccountid(Long.parseLong(user.getId()));
		genCart.setProductid(productid);
		genCart.setAmt(amt);
		
		//查询该产品是否已经在购物车中，如果已经在，就数量+1，如果没在，就加入购物车
		GenCart genCartBe = genCartService.getGenCartByProductIdAccountId(genCart);
		if (genCartBe == null) {
			genCartService.save(genCart);
		} else {
			genCartBe.setAmt(genCart.getAmt() + genCartBe.getAmt());
			genCartService.update(genCartBe);
		}
		
		List<GenCart> carts = genCartService.findList(genCart);
		CacheUtils.put(user.getId(), carts);
		
		session.setAttribute("carts", carts);
		session.setAttribute("count", carts.size());
		//返回信息
		Map<String,String> resultMap = new HashMap<String,String>();
		resultMap.put("message", Message.getContent("genCart.save"));
		resultMap.put("count", "" + carts.size());
		return resultMap;
	}
	
	@RequestMapping(value = "buyNow")
	public Object buyNow(String productIdHidden,HttpSession session,int buyAmt,
			Model model, RedirectAttributes redirectAttributes) {
		GenCart genCart = new GenCart();
		AccountInfo user = (AccountInfo)session.getAttribute("user");
		genCart.setAccountid(Long.parseLong(user.getId()));
		genCart.setProductid(productIdHidden);
		genCart.setAmt(buyAmt);
		
		GenCart genCartBe = genCartService.getGenCartByProductIdAccountId(genCart);
		if (genCartBe == null) {
			genCartService.save(genCart);
		} else {
			genCartBe.setAmt(genCart.getAmt() + genCartBe.getAmt());
			genCartService.update(genCartBe);
		}
		
		List<GenCart> carts = genCartService.findList(genCart);
		CacheUtils.put(user.getId(), carts);
		
		session.setAttribute("carts", carts);
		session.setAttribute("count", carts.size());
		return "redirect:"+Global.getFrontPath()+"/front/cart/genCart/?repage";
	}
	
	@RequestMapping(value = "deleteByIds")
	public String deleteByIds(String ids,HttpSession session, RedirectAttributes redirectAttributes) {
		if ("".equals(ids)) {
			return "redirect:"+Global.getFrontPath()+"/front/cart/genCart/?repage";
		}
		String[] idArr = ids.split(",");
		List<String> idLst = Arrays.asList(idArr);
		genCartService.deleteByIds(idLst);
		addMessage(redirectAttributes, Message.getContent("genCart.delete"));
		
		AccountInfo user = (AccountInfo)session.getAttribute("user");
		GenCart cart = new GenCart();
		cart.setAccountid(Long.parseLong(user.getId()));
		
		List<GenCart> carts = genCartService.findList(cart);
		CacheUtils.put(user.getId(), carts);
		
		
		session.setAttribute("carts", carts);
		session.setAttribute("count", carts.size());
		return "redirect:"+Global.getFrontPath()+"/front/cart/genCart/?repage";
	}

	@RequestMapping(value = "delete")
	public String delete(GenCart genCart,HttpSession session, RedirectAttributes redirectAttributes) {
		AccountInfo user = (AccountInfo)session.getAttribute("user");
		genCartService.delete(genCart);
		addMessage(redirectAttributes, Message.getContent("genCart.delete"));
		List<GenCart> carts = genCartService.findList(genCart);
		CacheUtils.put(user.getId(), carts);
		session.setAttribute("carts", carts);
		session.setAttribute("count", carts.size());
		return "redirect:"+Global.getFrontPath()+"/front/cart/genCart/?repage";
	}

	@RequestMapping(value = "form")
	public String form(GenCart genCart, Model model, RedirectAttributes redirectAttributes) {
		List<GenProduct> products = genProductService.findList(null);
		model.addAttribute("products", products);
		model.addAttribute("genCart", genCart);
		model.addAttribute("path", CommonParameter.uploadPath);
		return "modules/front/cart/genCartForm";
	}
	
	@RequestMapping(value = "reduce")
	@ResponseBody
	public Object reduce(GenCart genCart,HttpSession session) {
		AccountInfo user = (AccountInfo)session.getAttribute("user");
		genCart.setAmt(genCart.getAmt() - 1);
		genCartService.update(genCart);
		List<GenCart> carts = genCartService.findList(genCart);
		CacheUtils.put(user.getId(), carts);
		return null;
	}
	
	@RequestMapping(value = "plus")
	@ResponseBody
	public Object plus(GenCart genCart,HttpSession session) {
		AccountInfo user = (AccountInfo)session.getAttribute("user");
		genCart.setAmt(genCart.getAmt() + 1);
		genCartService.update(genCart);
		List<GenCart> carts = genCartService.findList(genCart);
		CacheUtils.put(user.getId(), carts);
		return null;
	}
	
	@RequestMapping(value = "inputNum")
	@ResponseBody
	public Object inputNum(GenCart genCart, HttpSession session) {
		AccountInfo user = (AccountInfo)session.getAttribute("user");
		genCartService.update(genCart);
		List<GenCart> carts = genCartService.findList(genCart);
		CacheUtils.put(user.getId(), carts);
		return null;
	}
	
	@RequestMapping(value="saveAddress")
	@ResponseBody
	public Object address(String defAdd,String receiverName,String receiverTelePhone,
			String province,String city,String countyTown,String detail,String accountId){
		AccountInfoAddress address = new AccountInfoAddress();
		address.setCity(city);
		address.setCountyTown(countyTown);
		address.setDetail(detail);
		address.setProvince(province);
		address.setAddUsername(receiverName);
		address.setAddTelnum(receiverTelePhone);
		
        if("true".equals(defAdd)){
            if(address.getAccountInfo()!=null){
                List<AccountInfoAddress> list= addressService.findListByAccountId(accountInfoService.get(address.getAccountInfo().getId())); 
                if(!list.isEmpty()){
                    for(AccountInfoAddress address1:list){
                        address1.setDefaultAddress(0);
                    }
                }
            }
            address.setDefaultAddress(1);
        }else{
            address.setDefaultAddress(0);
         }
   
        address.setAccountInfo(accountInfoService.get(accountId));
        addressService.save(address);
        Map<String,String> resultMap = new HashMap<String, String>();
        resultMap.put("message", "addSuccess");
        return resultMap;
    }
	
	@RequestMapping(value = "makeOrder")
	@Transactional
	public String makeOrder(GenCart genCart, Model model,HttpSession session, RedirectAttributes redirectAttributes) {
		String id = genCart.getId();
		model.addAttribute("id", id);
		if ("".equals(id)) {
			return null;
		}
		if(!Strings.isNullOrEmpty(id)){
			String ids[] = id.split(",");
			List<String> idsLst = Arrays.asList(ids);
			for (String cartId : ids) {
				GenCart genCart2 = genCartService.get(cartId);
				String productId = genCart2.getProductid();
				GenProduct product = genProductService.get(productId);
				if (genCart2.getAmt() > Long.parseLong(product.getStock())) {
					return "redirect:"+Global.getFrontPath()+"/front/cart/genCart?message=1";
				}
			}
			List<GenCart> genCarts = genCartService.getGenCartByIds(idsLst);
			model.addAttribute("genCarts", genCarts);
			AccountInfo user = (AccountInfo)session.getAttribute("user");
			//默认收货地址
			AccountInfoAddress defaultAddress = accountInfoAddressService.getAddressDefault(user);
			//全部收货地址
			List<AccountInfoAddress> commonAddresses= accountInfoAddressService.addressList(user);
			if(defaultAddress==null&&commonAddresses.size()>0){
			    model.addAttribute("defaultAddress", commonAddresses.get(0));
			}else{
			    model.addAttribute("defaultAddress", defaultAddress); 
			}
			 model.addAttribute("commonAddresses", commonAddresses);
			model.addAttribute("path", CommonParameter.uploadPath);
			Dict dict = new Dict();
			dict.setType(CommonParameter.transport_type);
		}
		model.addAttribute("shopOrder", new ShopOrder());
		return "modules/shop/marketOrder/marketOrder";
		
	}
	
	@RequestMapping(value = "order")
	@Transactional
	public String order(ShopOrder shopOrder,String cartid,
			String invoiceHead,
			Model model,HttpSession session,
			RedirectAttributes redirectAttributes) {
		AccountInfo user = (AccountInfo)session.getAttribute("user");
		String code = shopOrderService.getLastCode("","CODE","shop_order");
		shopOrder.setAccountId(user.getId());
		shopOrder.setCode(code);
		shopOrder.setCreateTime(new Date());
		shopOrder.setStatus(ShopOrderConstant.ORDER_WAIT_PAYMENT);
		
		if ("".equals(cartid)) {
			return null;
		}
		String ids[] = cartid.split(",");
		List<String> idsLst = Arrays.asList(ids);
		//获取选中的购物车商品信息
		List<GenCart> genCarts = genCartService.getGenCartByIds(idsLst);
		List<ShopOrderInfo> infos = new ArrayList<ShopOrderInfo>();
		for (GenCart genCart: genCarts) {
			ShopOrderInfo info = new ShopOrderInfo();
			info.setCode("CODE");
			info.setCount(genCart.getAmt());
			info.setImage(genCart.getPicture());
			info.setName(genCart.getProductName());
			info.setPrice(genCart.getPrice());
			info.setTotalAmount(genCart.getPrice() * genCart.getAmt());
			info.setProductId(genCart.getProductid());
			infos.add(info);
		}
		shopOrder.setShopOrderInfoList(infos);
		shopOrder.getShopOrderReceiving().setCode("");
		shopOrderService.productOrder(shopOrder);

		//删除购物车中的商品信息
		String[] idArrs = cartid.split(",");
		genCartService.deleteByIds(Arrays.asList(idArrs));
		
		GenCart genCart = new GenCart();
		genCart.setAccountid(Long.parseLong(user.getId()));
		List<GenCart> carts = genCartService.findList(genCart);
		CacheUtils.put(user.getId(), carts);
		session.setAttribute("carts", carts);
		session.setAttribute("count", carts.size());
		return   "redirect:" + frontPath + "/front/pay/showBank?id=" + shopOrder.getId(); 
	}
}